package com.gudong.performance.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gudong.performance.dao.entity.PerformanceInfo;
import com.gudong.performance.domain.PerformanceInfoDTO;
import com.gudong.performance.domain.ResultTable;
import com.gudong.performance.service.PerformanceService;
import com.gudong.performance.util.ExcelUtil;
import net.sf.jxls.util.Util;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类功能描述：
 *
 * @author：刘富国
 * @createTime：2019-04-02 10:03
 */
@Controller
@RequestMapping("performance")
public class PerformanceController {

    @Autowired
    private PerformanceService performanceService;

    @Autowired
    private ExcelUtil excelUtil;

    @ResponseBody
    @RequestMapping("list")
    public Object getPerformanceList(HttpServletRequest request) {
        ResultTable table = new ResultTable();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            Date date;
            String time = request.getParameter("time");
            if (!StringUtils.isEmpty(time) && !"undefined".equals(time)) {
                date = sdf.parse(request.getParameter("time"));
            } else {
                Calendar calendar = Calendar.getInstance();
                date = sdf.parse(sdf.format(calendar.getTime()));
            }
            List<PerformanceInfo> performanceList = performanceService.getPerformanceList(date);
            List<PerformanceInfoDTO> dtoList = new ArrayList<>();
            for (int i = 0; i < performanceList.size(); i++) {
                PerformanceInfoDTO dto = new PerformanceInfoDTO();
                BeanUtils.copyProperties(performanceList.get(i), dto);
                dto.setPerformanceDate(sdf2.format(performanceList.get(i).getPerformanceDate()));
                dtoList.add(dto);
            }
            table.setCode(0);
            table.setMsg("请求成功！");
            table.setCount(dtoList.size());
            table.setData(dtoList);
        } catch (Exception e) {
            table.setCode(1);
            table.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return table;
    }

    @RequestMapping("edit")
    public void editPerformance(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>(16);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PerformanceInfo info = new PerformanceInfo();
            info.setId(Integer.valueOf(request.getParameter("id")));
            info.setUserName(request.getParameter("userName"));
            info.setCompanyName(request.getParameter("companyName"));
            info.setNumber(request.getParameter("number"));
            info.setPerformanceDate(sdf.parse(request.getParameter("performanceDate")));
            info.setAmount(Double.valueOf(request.getParameter("amount")));
            performanceService.editPerformance(info);
            map.put("code", "0");
        } catch (Exception e) {
            map.put("code", "1");
            map.put("msg", e.getMessage());
            e.printStackTrace();
        }
        response.getWriter().print(JSONObject.toJSONString(map));
    }

    @RequestMapping("add")
    public void addPerformance(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>(16);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PerformanceInfo info = new PerformanceInfo();
            info.setUserName(request.getParameter("userName"));
            info.setCompanyName(request.getParameter("companyName"));
            info.setNumber(request.getParameter("number"));
            info.setPerformanceDate(sdf.parse(request.getParameter("performanceDate")));
            info.setAmount(Double.valueOf(request.getParameter("amount")));
            info.setStatus("1");
            info.setCreateTime(new Date());
            Integer id = performanceService.addPerformance(info);
            map.put("code", "0");
            if (id == null || id == 0) {
                map.put("code", "1");
                map.put("msg", "新增失败！");
            }
        } catch (Exception e) {
            map.put("code", "1");
            map.put("msg", e.getMessage());
            e.printStackTrace();
        }
        response.getWriter().print(JSONObject.toJSONString(map));
    }

    @RequestMapping("del")
    public void delPerformance(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>(16);
        try {
            String data = request.getParameter("data");
            List<PerformanceInfoDTO> dtoList = JSONArray.parseArray(request.getParameter("data"), PerformanceInfoDTO.class);
            List<Integer> idList = dtoList.stream().map(o -> o.getId()).collect(Collectors.toList());
            performanceService.delPerformance(idList);
            map.put("code", "0");
        } catch (Exception e) {
            map.put("code", "1");
            map.put("msg", e.getMessage());
            e.printStackTrace();
        }
        response.getWriter().print(JSONObject.toJSONString(map));
    }

    @RequestMapping("output")
    public void outputPerformance(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date date;
            if (!StringUtils.isEmpty(request.getParameter("time"))) {
                date = sdf.parse(request.getParameter("time"));
            } else {
                Calendar calendar = Calendar.getInstance();
                date = sdf.parse(sdf.format(calendar.getTime()));
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);


            HSSFWorkbook workbook = new HSSFWorkbook();
            //样式
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setDataFormat(workbook.createDataFormat().getFormat("General"));
            //样式
            HSSFCellStyle orangeStyle = workbook.createCellStyle();
            orangeStyle.setAlignment(HorizontalAlignment.CENTER);
            orangeStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            orangeStyle.setBorderBottom(BorderStyle.THIN);
            orangeStyle.setBorderLeft(BorderStyle.THIN);
            orangeStyle.setBorderRight(BorderStyle.THIN);
            orangeStyle.setBorderTop(BorderStyle.THIN);
            orangeStyle.setDataFormat(workbook.createDataFormat().getFormat("General"));
            orangeStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            orangeStyle.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
            //样式
            HSSFCellStyle yellowStyle = workbook.createCellStyle();
            yellowStyle.setAlignment(HorizontalAlignment.CENTER);
            yellowStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            yellowStyle.setBorderBottom(BorderStyle.THIN);
            yellowStyle.setBorderLeft(BorderStyle.THIN);
            yellowStyle.setBorderRight(BorderStyle.THIN);
            yellowStyle.setBorderTop(BorderStyle.THIN);
            yellowStyle.setDataFormat(workbook.createDataFormat().getFormat("General"));
            yellowStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            yellowStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

            HSSFSheet sheet = workbook.createSheet(calendar.get(Calendar.MONTH) + 1 + "月绩效表");
            createTitle(workbook, sheet, orangeStyle, calendar.get(Calendar.MONTH) + 1, calendar.getActualMaximum(Calendar.DATE));

            //新增数据行，并且设置单元格数据

            List<String> nameList = performanceService.getNameList(date);
            BigDecimal CountAmount = new BigDecimal(0);
            for (int i = 1; i <= nameList.size(); i++) {
                // 向工作表中添加数据
                HSSFRow row1 = sheet.createRow(2 * i - 1);
                HSSFRow row2 = sheet.createRow(2 * i);
                //向单元格加空值
                for (int j = 0; j < calendar.getActualMaximum(Calendar.DATE) + 2; j++) {
                    if (j == 0) {
                        row1.createCell(j).setCellStyle(yellowStyle);
                        row2.createCell(j).setCellStyle(yellowStyle);
                    } else {
                        row1.createCell(j).setCellStyle(style);
                        row2.createCell(j).setCellStyle(style);
                    }
                }

                row1.getCell(1).setCellValue(nameList.get(i - 1));
                row2.getCell(1).setCellValue("");

                List<PerformanceInfo> performanceInfoList = performanceService.getListByName(nameList.get(i - 1), date);
                BigDecimal userCountAmount = new BigDecimal(0);
                for (PerformanceInfo info : performanceInfoList) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(info.getPerformanceDate());
                    calendar.setTime(info.getPerformanceDate());
                    String row1Value = row1.getCell(c.get(Calendar.DATE) + 1).getStringCellValue();
                    String row2Value = row2.getCell(c.get(Calendar.DATE) + 1).getStringCellValue();
                    userCountAmount = userCountAmount.add(new BigDecimal(info.getAmount()));
                    if (StringUtils.isEmpty(row1Value)) {
                        row1.getCell(c.get(Calendar.DATE) + 1).setCellValue("" + info.getAmount().intValue());
                    } else {
                        row1.getCell(c.get(Calendar.DATE) + 1).setCellValue(row1Value + "、" + info.getAmount().intValue());
                    }
                    if (StringUtils.isEmpty(row2Value)) {
                        row2.getCell(c.get(Calendar.DATE) + 1).setCellValue(info.getCompanyName() + info.getNumber());
                    } else {
                        row2.getCell(c.get(Calendar.DATE) + 1).setCellValue(row2Value + "、" + info.getCompanyName() + info.getNumber());
                    }
                }
                row1.getCell(0).setCellValue(userCountAmount.setScale(0).toString());
                CountAmount = CountAmount.add(userCountAmount);
            }
            HSSFRow row = sheet.createRow(2 * nameList.size() + 2);
            row.createCell(0).setCellValue(CountAmount.setScale(0).toString());


            //删除空白列
            int countCell = calendar.getActualMaximum(Calendar.DATE) + 2;
            for (int j = 2; j < countCell; j++) {
                for (int i = 1; i < nameList.size() * 2 + 1; i++) {
                    String value = sheet.getRow(i).getCell(j).getStringCellValue();
                    if (!StringUtils.isEmpty(value)) {
                        break;
                    }
                    if (i == nameList.size() * 2 && StringUtils.isEmpty(value)) {
                        deleteColumn(sheet, j, 1);
                        --j;
                        --countCell;
                        break;
                    }

                }

            }


            String fileName = calendar.get(Calendar.MONTH) + 1 + "月绩效表.xls";

            //生成excel文件
            excelUtil.buildExcelFile(fileName, workbook);

            //浏览器下载excel
            excelUtil.buildExcelDocument(fileName, workbook, response);

        } catch (
                Exception e) {

        }

    }

    /**
     * 创建表头
     *
     * @param workbook
     * @param sheet
     */
    public void createTitle(HSSFWorkbook workbook, HSSFSheet sheet, HSSFCellStyle style, int month, int length) {
        HSSFRow row = sheet.createRow(0);
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        sheet.setColumnWidth(1, 12 * 256);
        sheet.setColumnWidth(3, 17 * 256);

        row.createCell(0).setCellValue("绩效总额");
        row.getCell(0).setCellStyle(style);
        row.createCell(1).setCellValue("姓名");
        row.getCell(1).setCellStyle(style);
        for (int i = 1; i <= length; i++) {
            row.createCell(i + 1).setCellValue(month + "." + i);
            row.getCell(i + 1).setCellStyle(style);
        }

//        for (int i = 0; i <= length + 1; i++) {
//            // 调整每一列宽度
//            sheet.autoSizeColumn((short) i);
//            // 解决自动设置列宽中文失效的问题
//            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
//        }

    }

    private static void deleteColumn(HSSFSheet sheet, int columnStartIndex, int columnNum) {
        Util.shiftCellsLeft(sheet, 0, columnStartIndex + columnNum, sheet.getPhysicalNumberOfRows() - 1, sheet.getRow(0).getPhysicalNumberOfCells() - 1, columnNum, true);
        Util.shiftCellsLeft(sheet, 0, sheet.getRow(0).getPhysicalNumberOfCells(), sheet.getPhysicalNumberOfRows() - 1, sheet.getRow(0).getPhysicalNumberOfCells() + columnNum, columnNum, true);
    }
}
